﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Common.Entitys.CommonLogs;
using Common.Entitys.Messages;
using Common.Utlis;
using Rougamo;
using Rougamo.Context;

namespace Common.Utils
{
    public class LoggingAttribute : MoAttribute
    {
        private FunctionLog FunctionLog = new FunctionLog();

        //private StringBuilder 

        public override void OnEntry(MethodContext context)
        {
            // 从context对象中能取到包括入参、类实例、方法描述等信息
            FunctionLog.EntryTime=DateTime.Now;
            FunctionLog.FunctionName = context.Method.ToString();
            
            string strArgument = "";
            foreach (object argument in context.Arguments)
            {
                FunctionLog.LisParas.Add(StringFormatHelp.ToString(argument));
            }

            //TimeSpan tsSpan = DateTime.Now - FunctionLog.EntryTime;

            //FunctionLog.FunctionName = $"{tsSpan.TotalMilliseconds}毫秒 {FunctionLog.FunctionName}";
            //ParameterInfo[] types = context.Method.GetParameters();
            //MessageAggregator<PromptMsg>.Publish($"方法{context.Method} 开始执行 入参{strArgument} 时间${DateTime.Now.ToString("yyyyMMdd HH: mm:ss: fff")}");

        }

        public override void OnSuccess(MethodContext context)
        {
            FunctionLog.ExitTime=DateTime.Now;
            if (context.HasReturnValue)
            {
                FunctionLog.ReturnValue = StringFormatHelp.ToString(context.ReturnValue);
            }
            LogHelp.AddLog(FunctionLog);
        }

        public override void OnException(MethodContext context)
        {
            FunctionLog.ExitTime = DateTime.Now;
            if (context.HasReturnValue)
            {
                FunctionLog.ReturnValue = StringFormatHelp.ToString(context.ReturnValue);
            }

            FunctionLog.HaveExcption = true;
            FunctionLog.ExcptionStrack = context.Exception.StackTrace;
            LogHelp.AddLog(FunctionLog);
            /// Log.Error("方法执行异常", context.Exception);
            // 从context对象中能取到包括入参、类实例、方法描述等信息

           // MessageAggregator<PromptMsg>.Publish($"进入方法{context.Method} 发生异常 时间${DateTime.Now.ToString("yyyyMMdd HH: mm:ss: fff")}");
        }

        public override void OnExit(MethodContext context)
        {
            // Log.Info("方法退出时，不论方法执行成功还是异常，都会执行");
          //  MessageAggregator<PromptMsg>.Publish($"方法{context.Method} 执行完成 时间${DateTime.Now.ToString("yyyyMMdd HH: mm:ss: fff")}");
        }

      
    }

    public class FullLoggingAttribute : LoggingAttribute
    {
        public override AccessFlags Flags => AccessFlags.All;
    }

    public interface ILogService : IRougamo<FullLoggingAttribute>
    {

    }
}
